/*
 * Copyright (c) 2023, 2024,yzc.cn All rights reserved.
 *
 */
package com.by.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Project: erp-cloud-api - BytesUtils</p>
 * <p>Powered by yzc On 2024-01-11 15:02:11</p>
 * <p>描述：<p>
 *
 * @author yzc [yzc0415@126.com]
 * @version 1.0
 * @since 17
 */
public class BytesUtils {

   private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将对象转换为byte[]数组
     * @param object
     * @return
     */
    public static byte[] getObjectBytes(Object object){

        String json = null;
        try {
            json = objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
        return bytes;

    }

    /**
     * 将map转换为byte[]数组
     * @param map
     * @return
     */
    public static byte[] getMapBytes(Map<String,Object> map){
        String json = null;
        try {
            json = objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
        return bytes;

    }

    /**
     * byte[]数组转换为Object对象
     * @param bytes
     * @return
     */
    public static  Object getObject(byte[] bytes){
        Object object = null;
        try {
            object = objectMapper.readValue(bytes, Object.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return object;
    }

    /**
     * 将byte[]转换为map
     * @param bytes
     * @return
     * @param <T>
     */
    public static <T> HashMap<String,T> getMap(byte[] bytes){
        HashMap<String,T> map =null;
        try {
            map = (HashMap<String, T>) objectMapper.readValue(bytes, new TypeReference<Map<String, T>>() {});
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return map;
    }

}
